package registry

import (
	"encoding/json"
	"fmt"
	"wf-deploy-agent/consts"
	"wf-deploy-agent/infra"
	"wf-deploy-agent/util"
)

type ServiceRegistration struct {
	Id                  string                 `json:"id"`
	Name                string                 `json:"name"`
	Address             string                 `json:"address"`
	Port                int32                  `json:"port"`
	SslPort             *int32                 `json:"sslPort"`
	Payload             map[string]interface{} `json:"payload"`
	RegistrationTimeUTC int64                  `json:"registrationTimeUTC"`
	ServiceType         string                 `json:"serviceType"`
	UriSpec             map[string]interface{} `json:"uriSpec"`
}

type ServiceInstance struct {
	InstanceId string                 `json:"instanceId"`
	ServiceId  string                 `json:"serviceId"`
	Host       string                 `json:"host"`
	Port       int32                  `json:"port"`
	Secure     bool                   `json:"secure"`
	UriSpec    map[string]interface{} `json:"uriSpec"`
}

func (instance *ServiceInstance) GetHostName() string {
	return fmt.Sprintf("%s:%d", instance.Host, instance.Port)
}

func (instance *ServiceInstance) GetHttpPrefix() string {
	if instance == nil {
		return ""
	}

	return fmt.Sprintf("%s%s:%d", consts.HttpProtocol, instance.Host, instance.Port)
}

func (instance *ServiceInstance) GetHttpsPrefix() string {
	if instance == nil {
		return ""
	}
	return fmt.Sprintf("%s%s:%d", consts.HttpsProtocol, instance.Host, instance.Port)
}

func (instance *ServiceInstance) GetHashCode() int {
	bytes, err := json.Marshal(instance)
	if err != nil {
		infra.Logger.Errorln(err)
		return 0
	}

	return util.GetHashCode(string(bytes))
}
